package com.yc.pay.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.yc.pay.config.YcPayConfig;
import com.yc.pay.service.INotifyPayService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 支付公司或银行回调支付结果
 */
@RestController
@RequestMapping("/payNotify")
public class PayNotifyController {

    private static final Logger logger = LoggerFactory.getLogger(PayNotifyController.class);

    @Autowired
    private YcPayConfig ycPayConfig;

    @Autowired
    private INotifyPayService notifyPayService;


    /**
     * 支付结果异步回调
     * @param request
     * @return
     */
    @RequestMapping("/result")
    public String recive(HttpServletRequest request){

        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }

            //乱码解决，这段代码在出现乱码时使用
            try {
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            } catch (UnsupportedEncodingException e) {
                logger.error("UnsupportedEncodingException",e);
            }
            params.put(name, valueStr);
        }
        logger.info("##########支付结果异步回调返回参数params：{}#########",params);


        //验证签名,判断请求是否支付宝发出来
        try {
            boolean flag =AlipaySignature.rsaCheckV1(params,ycPayConfig.getAlipayPubKey(),"utf-8","RSA2");
            if (!flag){
                return "fail";
            }

        } catch (AlipayApiException e) {
            logger.error("AlipayApiException",e);
            return "fail";
        }

        String rlt = notifyPayService.notify(params);



        return rlt;
    }



}
